package com.yanqu.road.dao.impl.union.activitygroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.utils.ServerType;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class UnionActivityGroupDaoImpl extends TempDataObjectDao<UnionActivityGroup> {

    public static String getUnionActivityGroupSql = "" +
            "SELECT t2.* " +
            "FROM t_s_activity_main t1 " +
            "LEFT JOIN t_s_union_activity_group t2 ON t1.activityId = t2.activityId " +
            "WHERE t1.endShowTime > ? AND t2.activityId IS NOT NULL ";

    public Map<Integer, Map<Integer, UnionActivityGroup>> getNoEndUnionActivityGroupMap(String selectTimeStr, int serverType, long serverId) {

        // 拼接sql
        String sql = getUnionActivityGroupSql;
        if (serverType == ServerType.SERVER_CROSS_2) { // 活动跨服
            sql += "AND t2.crossServerId = " + serverId + " ";
        } else if (serverType == ServerType.SERVER_GAME || serverType == ServerType.SERVER_AGENT) { // 游戏服 || 代理
            sql += "AND t2.serverSet LIKE '%" + serverId + "%' ";
        } else if (serverType == ServerType.CENTER_CROSS_2) { // 商会跨服
        } else {
            throw new RuntimeException();
        }

        Map<Integer, Map<Integer, UnionActivityGroup>> map = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setString(i++, selectTimeStr);
            rs = call.executeQuery();
            while (rs.next()) {
                UnionActivityGroup group = parse(rs);

                // 校验ID避免内网瞎配的ID用like出错
                if (serverType == ServerType.SERVER_GAME || serverType == ServerType.SERVER_AGENT) { // 游戏服 || 代理
                    if (!group.getServerSet().contains(serverId)) {
                        continue;
                    }
                }

                map.putIfAbsent(group.getActivityId(), new ConcurrentHashMap<>());
                map.get(group.getActivityId()).put(group.getGroupId(), group);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }

    public static String updateUnionActivityGroupSql = "update `t_s_union_activity_group` set crossServerId=?,serverSet=? where activityId=? and groupId=?";

    @Override
    protected boolean updateData(UnionActivityGroup unionActivityGroup) {
        unionActivityGroup.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getServerDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.INTEGER, unionActivityGroup.getCrossServerId()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(unionActivityGroup.getServerSet())));
        para.put(i++, new DbParameter(Types.INTEGER, unionActivityGroup.getActivityId()));
        para.put(i++, new DbParameter(Types.INTEGER, unionActivityGroup.getGroupId()));
        if (getDb().executeNoneQuery(updateUnionActivityGroupSql, para) > 0) {
            return true;
        }
        return false;
    }

    public static String insertUnionActivityGroupSql = "insert into `t_s_union_activity_group`(activityId,groupId,crossServerId,serverSet) values (?,?,?,?)";

    @Override
    protected boolean addData(UnionActivityGroup unionActivityGroup) {
        unionActivityGroup.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getServerDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.INTEGER, unionActivityGroup.getActivityId()));
        para.put(i++, new DbParameter(Types.INTEGER, unionActivityGroup.getGroupId()));
        para.put(i++, new DbParameter(Types.INTEGER, unionActivityGroup.getCrossServerId()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(unionActivityGroup.getServerSet())));
        if (getDb().executeNoneQuery(insertUnionActivityGroupSql, para) > 0) {
            return true;
        }
        return false;
    }

    @Override
    protected UnionActivityGroup parseData(ResultSet rs) throws SQLException {
        UnionActivityGroup unionActivityGroup = new UnionActivityGroup();
        unionActivityGroup.setActivityId(rs.getInt("activityId"));
        unionActivityGroup.setGroupId(rs.getInt("groupId"));
        unionActivityGroup.setCrossServerIdNeedSync(rs.getInt("crossServerId"));
        unionActivityGroup.setServerSetNeedSync(JSON.parseObject(rs.getString("serverSet"), new TypeReference<Set<Long>>() {
        }));
        return unionActivityGroup;
    }

    // ----------------------------------

    public Map<Integer, Integer> getGroupCrossIdMap(int activityId) {

        String sql = "select groupId,crossServerId from t_s_union_activity_group where activityId = ?";

        Map<Integer, Integer> map = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setInt(i++, activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                int groupId = rs.getInt("groupId");
                int crossServerId = rs.getInt("crossServerId");
                map.put(groupId, crossServerId);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }


    public Map<Integer, UnionActivityGroup> getUnionActivityGroupMap(int activityId, long gameServerId) {

        String sql = "SELECT * FROM t_s_union_activity_group WHERE activityId = ? AND serverSet LIKE '%" + gameServerId + "%' ";

        Map<Integer, UnionActivityGroup> map = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setInt(i++, activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                UnionActivityGroup group = parse(rs);

                // 校验ID避免内网瞎配的ID用like出错
                if (!group.getServerSet().contains(gameServerId)) {
                    continue;
                }

                map.put(group.getGroupId(), group);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }

}
